const plugin = requirePlugin('ppScale-plugin')
var app = getApp();
import tools from '../../tools/tools.js'
import { signUploadApi } from '../../api/clockIn'
import store from '../../utils/store'
Page({
  data: {
    // 选择的设备对象
    selmac: null,
    // 是否在测量中
    scaleing: false,
    // 测量心率测量状态
    state: 0,
    // 体重数据
    weight: '00.0',
    // 测量单位
    unit: 'kg',
    // 蓝牙连接状态
    devLink: false,
    // 体重数据
    currentWeight: 0,
    // 阻抗数据
    currentImpedance: 0,
    // 扫描筛选出的设备
    selectDev: null,
    // 设备模型
    deviceModel: null,
    // 锁定数据
    lastData: null,
    // 域名值
    domainValue: '',
    // wifi名
    wifiValue: '',
    // 密码值
    pwValue: '',
    // 单位数组
    deviceUnitArray: Object.keys(plugin.PPBluetoothDefine.PPDeviceUnit),
    // 单位数组下标
    deviceUnitIndex: 0,
    // 网络dialog
    netWorkFlag: false,
    // 域名dialog
    domainFlag: false,
    // 单位dialog
    unitFlag: false,
    // 调试log列表
    consoleList: [],
    // 获取设备数据传参
    param: {
      appKey: "lefu07bb12dd0842c9ed"
    },
    today: tools.formatDate(new Date()),
    blue: false,
  },
  confirmUpload() {
    // 点击“确认上传”后的逻辑，比如将测量数据上传到服务器
    const devParam = JSON.parse(this.data.lastData)
    console.log(this.data, 'this.data')
    this.refreshToken(() => {
      const resParam = {
        ...devParam,
        age: Number.parseInt(store.state.baseData.age),
        height: Number.parseInt(store.state.baseData.height),
        sex: store.state.baseData.sex == '男' ? 1: 0,
        weightKg: Number.parseInt(store.state.baseData.weight)
      }
      console.log(resParam, '参数')
      this.getAcLfBodyData(resParam)
    }, true)
    
    // 这里可添加真实的上传接口调用代码，示例仅做提示
    
  },
  reMeasure() {
    // 点击“重新测量”后的逻辑，比如重新连接设备、获取新数据等
    wx.showModal({
      title: '提示',
      content: '是否重新进行测量？',
      success: (res) => {
        if (res.confirm) {
          // 这里可添加重新测量的逻辑，比如调用设备相关 API 等
          wx.showToast({
            title: '重新测量中...',
            icon: 'loading',
            duration: 2000
          });
          // 模拟重新测量后更新数据，实际需结合设备通信
          setTimeout(() => {
            wx.showToast({
              title: '测量完成',
              icon: 'success'
            });
          }, 2000);
        }
      }
    });
  },
  // 去连接设备
  goConnectDevice() {
    let that = this
    wx.getSetting({
        success(res) {
            if (res.authSetting['scope.bluetooth']) {
                // 判断系统蓝牙是否开启，如果已经开启，则执行相关操作
                wx.openBluetoothAdapter({
                    success(res) {
                        that.setData({
                            blue: true
                        })
                        console.log("系统蓝牙权限已经打开")
                        wx.navigateTo({
                            url: '/clockInPage/connectWeight/connectWeight'
                        })
                    },
                    fail(res) {
                        that.setData({
                            blue: false
                        })
                        wx.showToast({
                            icon:"error",
                            title: '系统蓝牙权限未打开',
                          })
                    }
                })
            } else {
                that.setData({
                    blue: false
                })
                // 用户未授权，跳转到蓝牙授权设置页面
                wx.showToast({
                    icon:"error",
                    title: '蓝牙权限未打开',
                  })
                wx.openBluetoothAdapter({
                    success: (res) => {
                        that.setData({
                            blue: true
                        })
                    },
                    fail: (res) => {}
                })
            }
        }
    })


  },
  /**
   * 页面卸载时调用
   */
  onUnload() {
    // 业务结束后需要调用此方法
    plugin.Blue.stop()
  },

  /**
   * 页面隐藏时调用
   */
  onHide() {
    // 业务结束后需要调用此方法
    this.seeConsole('销毁蓝牙插件')
    plugin.Blue.stop()
  },
  onReady() {
    
  },
  onLoad() {
    let that = this
    wx.onBluetoothAdapterStateChange((res) => {
        console.log('adapterState changed, now is', res)
        that.setData({
            blue: res.available
        })
    })
  },
  async refreshToken(fn, flag) {
    let bodyToken = wx.getStorageSync('bodyToken');
    let bodyTokenTime = wx.getStorageSync('bodyTokenTime');
    if (!bodyToken || bodyTokenTime * 1000 < +new Date() || flag) {
        let res = await plugin.refreshToken({
            url: 'https://uniquehealth.lefuenergy.com',
            data: {
                "appSecret": "g6v1QITkOhoo9Qp7Bwh9cgNVHyIBi02Tr8zH4Gi12Wk=",
                "appKey": "lefu07bb12dd0842c9ed"
            }
        });
        console.log("res", res);
        if (res.data.code == 200) {
            wx.setStorageSync('bodyToken', res.data.data.token);
            wx.setStorageSync('bodyTokenTime', res.data.data.expireTime);
            fn();
        }
    } else {
        fn();
    }
 },
  getAcLfBodyData(param) {
    let bodyToken = wx.getStorageSync('bodyToken');
    wx.request({
      url: 'https://uniquehealth.lefuenergy.com/openapi-bodydata/bodyData/V1_7_1/getAcLfBodyData8',
      data: param,
      method: 'GET',
      header: {
        "token": bodyToken,
        "Accept-Language": 'zh'
      },
      success(res) {
        console.log(res, '数据')
        res.data.studentId = store.state.studentId
        signUploadApi(res.data).then((data)=>{
          wx.showToast({
            title: '上传成功',
            icon: 'success'
          });
        })
      }
    })
  },
  onShow() {
    // 高于1.0.5版本 如无法扫描设备 需请求获取并设置最新设备配置列表
    // this.getDeviceSettingList(this.data.param)
    // 高于1.0.5版本 如无法扫描设备 直接设置最新设备列表
    // plugin.Blue.setDeviceSetting([{"createBy":null,"createTime":"2023-09-14 11:38:56","updateBy":null,"updateTime":"2023-10-18 16:08:39","remark":null,"id":12,"deviceName":"LFSmart Scale","sign":"CF4303","advLength":20,"macAddressStart":7,"deviceConnectType":2,"deviceType":1,"deviceProtocolType":2,"deviceCalcuteType":3,"devicePowerType":2,"deviceFuncType":75,"deviceAccuracyType":2,"deviceUnitType":"0,3","calorieStatus":1,"uhStatus":1,"status":0,"imgUrl":"https://unique.lefuenergy.com/dev/2023/09/28/4dianji_border_20230928102849A007.png"}])
    // 使用节流函数包装测重事件处理函数
    let throttledScroll = this.throttle(this.handleProgress, 1500);
    // 记录设备对象
    this.setData({
      selmac: app.globalData.selmac
    })
    // 蓝牙状态监听
    wx.onBluetoothAdapterStateChange((res) => {
      if (!res.available) {
        this.seeConsole('蓝牙设备断开')
      }
    })
    // 是否开启插件日志
    plugin.Blue.visibleLog()
    this.seeConsole('开启蓝牙开始扫描设备')
    // 获取扫描设备列表
    plugin.bus.subscribe("devicesList", (devList) => {
      // 根据deviceId查找匹配设备
      let selectDev = devList.find(item => {
        return item.deviceId == this.data.selmac.deviceId
      })
      // 记录选择出设备
      this.setData({
        selectDev: selectDev
      })
      if (!this.data.deviceModel && this.data.selectDev) {
        //获取与保存秤类型
        this.seeConsole('获取秤端设备模型')
        // 获取与记录设备模型
        this.setData({
          deviceModel: plugin.Blue.getDeviceModel(selectDev)
        })
      }
      // 匹配广播秤
      if (this.data.deviceModel && this.data.deviceModel.deviceConnectType == plugin.PPBluetoothDefine.PPDeviceConnectType
        .PPDeviceConnectTypeBleAdv) {
        this.seeConsole('设备连接广播秤')
        //   广播秤 匹配与数据监听
        plugin.Blue.setbroadcastDev(selectDev)
      }
      // 匹配连接秤
      if (this.data.deviceModel && this.data.deviceModel.deviceConnectType == plugin.PPBluetoothDefine.PPDeviceConnectType
        .PPDeviceConnectTypeBleConnect) {
        // 停止扫描
        this.seeConsole('停止扫描')
        plugin.Blue.stopBluetoothDevicesDiscovery()
        // 连接设备
        this.seeConsole('开始连接设备')
        plugin.Blue.createBLEConnection(selectDev)
      }
    });
    
    // 设备链接回调
    plugin.bus.subscribe("deviceConnect", (res) => {
      this.seeConsole('成功连接设备')
      // 开启监听蓝牙秤数据 必填
      plugin.ScaleAction.startDataProgress()
      setTimeout(() => {
        plugin.ScaleAction.syncDeviceSetting({
          unit: +this.data.deviceUnitIndex,
        })
      }, 800)
    });

    // 设备链接回调
    plugin.bus.subscribe("devicesModel", (res) => {
      // console.log("res",res)
    });

    // 监听秤端数据回调
    plugin.bus.subscribe("progressData", (res) => {
      throttledScroll()
      // console.log("selectDev",this.data.selectDev)
      // console.log("selectDev",plugin.Blue.getDeviceModel(this.data.selectDev))
      if (this.data.selectDev) {
        // 广播秤类型连接
        if (this.data.deviceModel && this.data.deviceModel.deviceConnectType == plugin.PPBluetoothDefine.PPDeviceConnectType
          .PPDeviceConnectTypeBleAdv) {
          this.setData({
            devLink: true
          })
        }
        if (res.weight > 0) {
          // 有数据显示为测量中
          this.setData({
            scaleing: true
          })
          // 记录体重数据
          this.setData({
            weight: (res.weight / 100).toFixed(2)
          })
          // 获取测量过程秤显示单位
          this.setData({
            unit: this.getKeyByUnit(res.unit)
          })
        } else {
          // 无数据显示为未测量
          this.setData({
            state: 0
          })
          // 无数据显示为未测量
          this.setData({
            scaleing: false
          })
        }
        if (res.isHeartRating) {
          // 心率测量中状态设置
          this.setData({
            state: 1
          })
        }
      }
    });

    // 设备自动断开监听
    plugin.bus.subscribe("deviceWillDisconnect", (res) => {
      this.seeConsole('设备自动断开连接')
      //   设备自动断连后重连
      this.setData({
        devLink: false
      })
      // 重新连接方法
      this.reconnectDevice()
    })

    // 锁定数据
    plugin.bus.subscribe("lockData", (res) => {
      this.seeConsole('锁定测量数据:' + JSON.stringify(res))
      // 测量结束
      this.setData({
        currentWeight: (res.weight / 100).toFixed(2)
      })
      // 记录阻抗值
      this.setData({
        currentImpedance: res.resistance
      })
      // 记录测量结果数据
      this.setData({
        lastData: JSON.stringify(res)
      })
      // 状态还原
      this.setData({
        state: 0
      })
      this.setData({
        scaleing: false
      })

    });
    // 蓝牙连接状态监听
    plugin.bus.subscribe("connectState", (res) => {
      // 连接状态
      if (this.data.selectDev) {
        if (res == plugin.BLUE_STATE.TRANSMITDATA || res == plugin.BLUE_STATE.LOCKDATA || res == plugin.BLUE_STATE
          .HEARTRATING || res ==
          plugin.BLUE_STATE.CONNECTSUCCESS || res == plugin.BLUE_STATE.WIFISUCCESS) {
          this.setData({
            devLink: true
          })
        } else {
          this.setData({
            devLink: false
          })
        }
        // 连接失败则重新连接
        if (res == plugin.BLUE_STATE.CONNECTFAILED) {
          this.reconnectDevice()
        }
      }
    });
    // 秤端操作回调
    plugin.bus.subscribe("syncDeviceSetting", (res) => {
      this.seeConsole('成功配置设备')
    })
    plugin.bus.subscribe("snData", () => {
      this.seeConsole('成功配置wifi网络')
    })
    plugin.bus.subscribe("domainChange", () => {
      this.seeConsole('成功更新秤端请求服务器域名')
    })
    plugin.bus.subscribe("syncDeviceTimeSuccess", () => {
      this.seeConsole('成功同步时间')
    })
    plugin.bus.subscribe("syncDeviceHistorySuccess", (e) => {
      console.log("历史列表", e)
      this.seeConsole('成功同步历史')
    })
    plugin.bus.subscribe("deviceInfo", (res) => {
      console.log("deviceInfo", res)
      this.seeConsole('设备信息')
    })

    plugin.bus.subscribe("deleteDeviceHistoryDataSuccess", () => {
      this.seeConsole('成功删除同步历史')
    })
    // 开始扫描
    plugin.Blue.start([], false)

  },
  connect() {
    this.seeConsole('开始连接设备')
    if (this.data.deviceModel && this.data.deviceModel.deviceConnectType == plugin.PPBluetoothDefine.PPDeviceConnectType
      .PPDeviceConnectTypeBleConnect) {
      // 连接设备
      plugin.Blue.createBLEConnection(this.data.selectDev)
    }
  },
  disconnect() {
    this.seeConsole('断开连接')
    plugin.Blue.disconnect()
  },
  switchUnit() {
    this.setData({
      unitFlag: true
    })
  },
  setUserMes() {
    this.seeConsole('下发用户信息')
    if (this.data.devLink) {
      // 根据设备已有单位切换 
      plugin.ScaleAction.syncDeviceSetting({
        age: 28,
        height: 167,
        gender: 1,
      })
    } else {
      this.seeConsole('停止下发用户信息')
      wx.showToast({
        title: '需要连接蓝牙秤',
        icon: 'error',
        duration: 1000,
        mask: true
      })
    }
  },
  syncHistory() {
    this.seeConsole('同步历史')
    if (this.data.devLink) {
      // 根据设备已有单位切换 
      plugin.ScaleAction.fetchDeviceHistoryData()
    } else {
      this.seeConsole('停止同步历史')
      wx.showToast({
        title: '需要连接蓝牙秤',
        icon: 'error',
        duration: 1000,
        mask: true
      })
    }
  },
  deleteSyncHistory() {
    this.seeConsole('删除同步历史')
    if (this.data.devLink) {
      // 根据设备已有单位切换 
      plugin.ScaleAction.deleteDeviceHistoryData()
    } else {
      this.seeConsole('停止删除同步历史')
      wx.showToast({
        title: '需要连接蓝牙秤',
        icon: 'error',
        duration: 1000,
        mask: true
      })
    }
  },
  syncTime() {
    this.seeConsole('同步时间')
    if (this.data.devLink) {
      // 根据设备已有单位切换 
      plugin.ScaleAction.startDataProgress()
    } else {
      this.seeConsole('停止同步时间')
      wx.showToast({
        title: '需要连接蓝牙秤',
        icon: 'error',
        duration: 1000,
        mask: true
      })
    }
  },
  configureNetwork() {
    this.setData({
      netWorkFlag: true
    })
  },
  modifyDNS() {
    this.setData({
      domainFlag: true
    })
  },
  /**
   * 重新连接设备
   */
  reconnectDevice() {
    this.seeConsole('尝试重新连接')
    // 设备断开连接后重新连接
    plugin.Blue.disconnect((disres) => {
      if (disres.errCode == 0) {
        this.seeConsole('开始扫描设备')
        plugin.Blue.startBluetoothDevicesDiscovery()
      } else {
        this.reconnectDevice()
      }
    })
  },

  /**
   * 根据单位值获取设备单位描述
   * @param  {number} unit 单位值
   * @return {string}      单位描述
   */
  getKeyByUnit(unit) {
    for (const key in plugin.PPBluetoothDefine.PPDeviceUnit) {
      if (plugin.PPBluetoothDefine.PPDeviceUnit[key] === unit) {
        return key;
      }
    }
    return null;
  },
  bindKeyInput: function (e) {
    this.setData({
      inputValue: e.detail.value
    })
  },
  bindDomainInput: function (e) {
    this.setData({
      domainValue: e.detail.value
    })
  },
  bindWifiInput: function (e) {
    this.setData({
      wifiValue: e.detail.value
    })
  },
  bindPasswdInput: function (e) {
    this.setData({
      pwValue: e.detail.value
    })
  },
  bindPickerChange: function (e) {
    this.setData({
      deviceUnitIndex: e.detail.value
    });
  },
  changeUnit() {
    this.seeConsole('切换单位')
    if (this.data.devLink) {
      // 根据设备已有单位切换 
      plugin.ScaleAction.syncDeviceSetting({
        unit: +this.data.deviceUnitIndex,
      })

    } else {
      this.seeConsole('停止切换单位')
      wx.showToast({
        title: '需要连接蓝牙秤',
        icon: 'error',
        duration: 1000,
        mask: true
      })
    }
    this.setData({
      unitFlag: false
    })
  },
  configWifi() {
    this.seeConsole('开始配置wifi')
    // 配置wifi
    if (this.data.devLink && this.data.wifiValue && this.data.pwValue) {
      console.log("this.data.wifiValue && this.data.pwValue", this.data.wifiValue, this.data.pwValue)
      plugin.ScaleAction.configWifi(this.data.wifiValue, this.data.pwValue)
    } else {
      this.seeConsole('停止配置wifi')
      wx.showToast({
        title: '需要连接蓝牙秤或wifi名称或密码',
        duration: 1000,
        mask: true
      })
    }
    this.setData({
      netWorkFlag: false
    })
  },
  changeDomain() {
    this.seeConsole('开始配置域名')
    // 配置域名
    if (this.data.domainValue != '' && this.data.devLink) {
      plugin.ScaleAction.configDomain(this.data.domainValue.replace(/^(https?:\/\/)/, ""))
    } else {
      this.seeConsole('停止配置域名')
      wx.showToast({
        title: '需要连接蓝牙秤或输入域名',
        duration: 1000,
        mask: true
      })
    }
    this.setData({
      domainFlag: false
    })
  },
  // 节流函数
  throttle: function (func, delay) {
    let timer = null;
    let lastTime = 0;
    return function () {
      const now = Date.now();
      if (now - lastTime >= delay) {
        func();
        lastTime = now;
      } else {
        clearTimeout(timer);
        timer = setTimeout(func, delay);
      }
    };
  },
  // 测量中体重记录
  handleProgress: function () {
    this.seeConsole('正在测量体重:' + this.data.weight)
  },
  seeConsole(string) {
    this.setData({
      consoleList: [string].concat(this.data.consoleList)
    })
  },
  /**
   * 清除控制台
   */
  clear() {
    this.setData({
      consoleList: []
    })
  },
  /**
   * 刷新token
   * @param  {function} fn   获取token后执行函数
   * @param  {boolean}  flag 请求刷新token
   */
  async refreshToken(fn, flag) {
    let bodyToken = wx.getStorageSync('bodyToken');
    let bodyTokenTime = wx.getStorageSync('bodyTokenTime');
    if (!bodyToken || bodyTokenTime * 1000 < +new Date() || flag) {
      let res = await plugin.refreshToken({
        url: 'https://uniquehealth.lefuenergy.com',
        data: {
          "appSecret": "g6v1QITkOhoo9Qp7Bwh9cgNVHyIBi02Tr8zH4Gi12Wk=",
          "appKey": "lefu07bb12dd0842c9ed"
        }
      });
      console.log("res", res);
      if (res.data.code == 200) {
        wx.setStorageSync('bodyToken', res.data.data.token);
        wx.setStorageSync('bodyTokenTime', res.data.data.expireTime);
        fn();
      }
    } else {
      fn();
    }
  },
  getDeviceSettingList(param) {
    let bodyToken = wx.getStorageSync('bodyToken');
    plugin.getDeviceSettingList({
      url: 'https://uniquehealth.lefuenergy.com',
      data: param,
      header: {
        "token": bodyToken,
        "Accept-Language": wx.getStorageSync("lang") || 'zh'
      }
    }).then(this.handleResponse);
  },
  handleResponse(res) {
    if (res.data.code == 200) {
      // 配置蓝牙设备列表
      plugin.Blue.setDeviceSetting(res.data.data)
    } else if (res.data.code == 401) {
      // token过期 重新请求token解析数据
      this.refreshToken(() => {
        this.getDeviceSettingList(this.data.param)
      }, true);
    }
  },
});